import React, { Component } from "react";

import FilterFooter from "../../../../components/FilterFooter";

import styles from "./index.module.css";
import { Spring } from "react-spring/renderprops";

export default class FilterMore extends Component {
  state = {
    selectedValues: this.props.defaultValue,
  };
  // 点击标签的事件逻辑
  onTagClick(value) {
    const { selectedValues } = this.state;
    // 创建新数组
    const newSelectedValues = [...selectedValues];
    const index = newSelectedValues.indexOf(value);
    if (index === -1) {
      // 没有当前项的值
      newSelectedValues.push(value);
    } else {
      newSelectedValues.splice(index, 1);
    }
    this.setState({
      selectedValues: newSelectedValues,
    });
  }
  // 清除按钮的事件逻辑
  onCancel = () => {
    this.setState({
      selectedValues: [],
    });
  };

  // 确定按钮的事件逻辑
  onOK = () => {
    const { type, onSave } = this.props;
    // onSave 是父组件的方法
    onSave(type, this.state.selectedValues);
  };

  // 渲染标签
  renderFilters(data) {
    const { selectedValues } = this.state;
    // 高亮类名 :styles.tagActive
    return data.map((item) => {
      const isSelected = selectedValues.indexOf(item.value) > -1;
      return (
        <span
          key={item.value}
          className={[styles.tag, isSelected ? styles.tagActive : ""].join(" ")}
          onClick={() => this.onTagClick(item.value)}
        >
          {item.label}
        </span>
      );
    });
  }

  

  render() {
    const {
      data: { roomType, oriented, floor, characteristic },
      onCancel,
      type,
    } = this.props;
    const isOpen = type === "more";
   
    return (
      <div className={styles.root}>
        {/* 遮罩层 */}
          <Spring to={{ opacity: isOpen ? 1 : 0 }}>
          {props => {
            if (props.opacity === 0) {
              return null
            }

            return (
              <div
                style={props}
                className={styles.mask}
                onClick={() => onCancel(type)}
              />
            )
          }}
        </Spring>

        {/* 条件内容 */}
        <div className={styles.tags}>
          <dl className={styles.dl}>
            <dt className={styles.dt}>户型</dt>
            <dd className={styles.dd}>{this.renderFilters(roomType)}</dd>
            <dt className={styles.dt}>朝向</dt>
            <dd className={styles.dd}>{this.renderFilters(oriented)}</dd>{" "}
            <dt className={styles.dt}>楼层</dt>
            <dd className={styles.dd}>{this.renderFilters(floor)}</dd>
            <dt className={styles.dt}>房屋</dt>
            <dd className={styles.dd}>{this.renderFilters(characteristic)}</dd>
          </dl>
        </div>

        {/* 底部按钮 */}
        <FilterFooter
          className={styles.footer}
          cancelText="清除"
          onCancel={this.onCancel}
          onSave={this.onOK}
        />
      </div>
    );
  }
}
